/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bingoogolapple.qrcode.core;

import ohos.app.Context;
import ohos.app.Environment;
import ohos.global.resource.NotExistException;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.io.*;
import java.util.Optional;
import java.util.UUID;

/**
 * 资源文件工具类
 */
public class ResourceUtil {

    /**
     * 复制文件到指定的文件夹下
     *
     * @param context 上下文
     * @param src 资源文件
     * @param des 资源文件名
     * @return 文件路径
     */
    public static String copyResourceToExtDir(Context context, String src, String des){
        LogUtil.info("src:"+src);
        String res = "";
        RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry(src);
        if (rawFileEntry != null) {
            FileOutputStream fos=null;
            try {
                Resource resource = rawFileEntry.openRawFile();
                File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + File.separator + des);
                if (!file.exists()) {
                    fos = new FileOutputStream(file);
                    byte[] b1 = new byte[1024];
                    int length = 0;
                    while ((length = resource.read(b1)) != -1) {
                        fos.write(b1, 0, length);
                    }
                }
                res = file.getPath();
                LogUtil.info("res:" + res);
                return res;
            } catch (IOException ex) {
                LogUtil.error("err:"+ex.getMessage());
                return res;
            }finally {
                try {
                    if(fos!=null){
                        fos.close();
                    }
                } catch (IOException ex) {
                    LogUtil.error("err:"+ex.getMessage());
                }
            }
        }
        return res;
    }

    /**
     * 根据资源路径获取输入流
     *
     * @param context 上下文
     * @param src 资源路径
     * @return 输入流对象
     */
    public static InputStream getResourceInput(Context context, String src){
        Resource resource = null;
        try {
            RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry(src);
            resource = rawFileEntry.openRawFile();
        }catch (Exception e)
        {
            LogUtil.error("err:"+e.getMessage());
        }
        return resource;
    }

    /**
     * 根据输入路径获取图片文件
     *
     * @param context 上下文
     * @param src 资源文件
     * @return pixelMap对象
     */
    public static PixelMap getPixelMapByResPath(Context context, String src){
        PixelMap pixelMap = null;
        InputStream resource = getResourceInput(context,src);
        ImageSource imageSource = ImageSource.create(resource, null);
        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        pixelMap = imageSource.createPixelmap(decodingOpts);
        return pixelMap;
    }

    /**
     * 根据资源文件id获取图片文件
     *
     * @param context 上下文
     * @param id 资源文件id
     * @return pixelMap对象
     */
    public static PixelMap decodeResource(Context context, int id) {
        try {
            String path = context.getResourceManager().getMediaPath(id);
            if (path.isEmpty()) {
                return null;
            }
            RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path);
            ImageSource.SourceOptions options = new ImageSource.SourceOptions();
            options.formatHint = "image/png";
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            Resource asset = assetManager.openRawFile();
            ImageSource source = ImageSource.create(asset, options);
            return Optional.ofNullable(source.createPixelmap(decodingOptions)).get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转成图片
     * @param context context
     * @param mResource mResource
     * @return PixelMap
     * @throws IOException ex
     * @throws NotExistException ex
     */
    public static PixelMap getPixelmap(Context context, int mResource) throws IOException, NotExistException {
        ResourceManager rsrc = context.getResourceManager();
        if (rsrc == null) {
            return null;
        }
        Resource resource = null;
        if (mResource != 0) {
            resource = rsrc.getResource(mResource);
        }
        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
        ImageSource imageSource = null;
        try {
            imageSource = ImageSource.create(readResource(resource), srcOpts);
        } finally {
            close(resource);
        }
        if (imageSource == null) {
            throw new FileNotFoundException();
        }
        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        decodingOpts.desiredSize = new Size(0, 0);
        decodingOpts.desiredRegion = new ohos.media.image.common.Rect(0, 0, 0, 0);
        decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888;

        PixelMap pixelmap = imageSource.createPixelmap(decodingOpts);
        return pixelmap;
    }

    private static byte[] readResource(Resource resource) {
        final int bufferSize = 1024;
        final int ioEnd = -1;

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[bufferSize];
        while (true) {
            try {
                int readLen = resource.read(buffer, 0, bufferSize);
                if (readLen == ioEnd) {
                    break;
                }
                output.write(buffer, 0, readLen);
            } catch (IOException e) {
                LogUtil.error(e.getMessage());
                break;
            } finally {
                try {
                    output.close();
                } catch (IOException e) {
                    LogUtil.error(e.getMessage());
                }
            }
        }
        return output.toByteArray();
    }

    private static void close(Resource resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                LogUtil.error(e.getMessage());
            }
        }
    }



    /**
     * 根据存在的路径创建pixelMap
     * @param context 上下文
     * @param src 已存在路径
     * @return pixelMap对象
     */
    public static PixelMap getPixelMapByExtPath(Context context, String src){
        PixelMap pixelMap = null;
        ImageSource imageSource0 = ImageSource.create(src, (ImageSource.SourceOptions)null);
        pixelMap = imageSource0.createPixelmap((ImageSource.DecodingOptions)null);
        return pixelMap;
    }

    /**
     * 保存文件
     *
     * @param context 上下文对象
     * @param bytes 字节数组
     */
    public static void saveDebugFile(Context context, byte[] bytes){
        LogUtil.error("before SaveDebugFile");
        String fileName = "file_" + UUID.randomUUID() + ".debug";
        File targetFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName);
        try (FileOutputStream output = new FileOutputStream(targetFile)) {
            output.write(bytes);

        } catch (IOException e) {
            LogUtil.error( "Save image failed");
        }
    }


}
